package io.seata.order.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.order.client.ProductClient;
import io.seata.order.entity.Order;
import io.seata.order.mapper.OrderMapper;
import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author bruce.wang
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService{

    @Autowired
    private ProductClient productClient;

    @Autowired
    private OrderMapper orderMapper;

    //这里切记不要加@GlobalTransactional
    @Transactional(rollbackFor = Exception.class)
    @ShardingTransactionType(TransactionType.BASE)
    public void seataDemo(Boolean hasError) {
        //下单操作
        Order order = new Order();
        order.setOrderName("测试数据");
        order.setBuyNum(2);
        orderMapper.insert(order);

        //减库存（这里参数什么的就自己脑补了）
        productClient.minusStock();

        //异常模拟
        if(hasError){
            int i=1/0;
        }
    }

    /**
     * 查询所有订单
     * @return
     */
    public List<Order> listAll() {
        //查询所有订单
//        LambdaQueryWrapper wrapper = new QueryWrapper<Order>().lambda();
        QueryWrapper<Order> queryWrapper = new QueryWrapper<Order>();
//        Map<String, Object> map = new HashMap<>();
        return orderMapper.selectList(queryWrapper);
//        return orderMapper.selectList(wrapper);
    }

    /**
     * 如果查询条件中分库分库分表键被设置为null，就会报错
     * queryWrapper.eq("id", null);
     *
     * @param query
     * @return
     */
    public List<Order> selectByConditon(Order query) {
        //查询所有订单
        QueryWrapper<Order> queryWrapper = new QueryWrapper<Order>();
        if (null != query.getId()) {
            queryWrapper.eq("id", query.getId());
        }
        if (null != query.getOrderName()) {
            queryWrapper.eq("order_name", query.getOrderName());
        }
//        Map<String, Object> map = new HashMap<>();
        return orderMapper.selectList(queryWrapper);
//        return orderMapper.selectList(wrapper);
    }

    /**
     * 查询所有订单
     * @return
     */
    public List<Order> listPage() {

        //查询所有订单
//        LambdaQueryWrapper wrapper = new QueryWrapper<Order>().lambda();
        QueryWrapper<Order> queryWrapper = new QueryWrapper<Order>();
//        Map<String, Object> map = new HashMap<>();
        return orderMapper.selectList(queryWrapper);
//        return orderMapper.selectList(wrapper);
    }
}
